<div class="layui-fluid" lay-title="添加田间服务信息">
	<div class="layui-card">
		<div class="layui-card-body" style="padding: 15px;">
			<fieldset class="layui-elem-field layui-field-title">
				<legend class="addTitle">添加田间服务信息</legend>
			</fieldset>
			<form class="layui-form addServiceMsg" action="" lay-filter="addServiceMsgForm">
				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">时间&nbsp;<span class="nepadmin-c-red">*</span></label>
						<div class="layui-input-inline">
							<input type="text" name="guide_time" id="form-group-date" lay-verify="date" autocomplete="off" class="layui-input">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">物候期</label>
						<div class="layui-input-inline">
							<input type="text" name="phenological_phase" autocomplete="off" class="layui-input">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">土壤湿度</label>
						<div class="layui-input-inline">
							<input type="tel" name="soil_humidity" autocomplete="off" class="layui-input">
						</div>
					</div>
				</div>

				<div class="layui-form-item">
					<label class="layui-form-label">土壤监测数据</label>
					<div class="layui-input-block">
						<input type="text" name="soil_monitoring" placeholder="" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">树势现状&nbsp;<span class="nepadmin-c-red">*</span></label>
					<div class="layui-input-block">
						<input type="text" name="sapling_desc" placeholder="" lay-verify="required" autocomplete="off" class="layui-input">
					</div>
				</div>


				<div class="layui-form-item">
					<div class="layui-inline">
						<label class="layui-form-label">挂果量</label>
						<div class="layui-input-inline">
							<input type="text" name="fruit_quantity" autocomplete="off" class="layui-input">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">肥水基础设施</label>
						<div class="layui-input-inline">
							<input type="text" name="fertilization_facility" autocomplete="off" class="layui-input longInput">
						</div>
					</div>
				</div>


				<div class="layui-form-item">
					<label class="layui-form-label">近期农事操作</label>
					<div class="layui-input-block">
						<input type="text" name="recently_operation" placeholder="" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">近期肥水管理</label>
					<div class="layui-input-block">
						<input type="text" name="recently_fertilization" placeholder="" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">近期病虫害防治</label>
					<div class="layui-input-block">
						<input type="text" name="recently_defend" placeholder="" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">管理操作进度</label>
					<div class="layui-input-block">
						<input type="text" name="manage_operation" placeholder="" autocomplete="off" class="layui-input">
					</div>
				</div>
				<div class="layui-form-item layui-form-text">
					<label class="layui-form-label">生长现状</label>
					<div class="layui-input-block">
						<div class="layui-upload  uploadImgBlock">
							<button type="button" class="layui-btn" id="uploadImg">多图片上传</button>
							<button type="button" class="layui-btn" id="test2" style="display: none;">多图片上传</button>
							<blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
								预览图：
								<div class="layui-upload-list" id="uploadQuestImg"></div>
							</blockquote>
							<input type="file" id="btnHide" multiple accept="image/*" class="none" style="display: none" />
							<div  id='comElemImg'>
								<input type="file" style="display: none" />
							</div>
							
						</div>
					</div>
				</div>

				<div class="layui-form-item layui-form-text">
					<label class="layui-form-label">问题发现</label>
					<div class="layui-input-block">
						<textarea name="issue" placeholder="请输入内容" class="layui-textarea"></textarea>
					</div>
				</div>

				<div class="layui-form-item layui-form-text">
					<label class="layui-form-label">下期农事操作建议</label>
					<div class="layui-input-block">
						<textarea name="next_operation" placeholder="请输入内容" class="layui-textarea"></textarea>
					</div>
				</div>
				<div class="layui-form-item layui-form-text">
					<label class="layui-form-label">下期肥水管理建议</label>
					<div class="layui-input-block">
						<textarea name="next_fertilization" placeholder="请输入内容" class="layui-textarea"></textarea>
					</div>
				</div>
				<div class="layui-form-item layui-form-text">
					<label class="layui-form-label">下期病虫害防治建议</label>
					<div class="layui-input-block">
						<textarea name="next_defend" placeholder="请输入内容" class="layui-textarea"></textarea>
					</div>
				</div>
				<div class="layui-form-item layui-form-text">
					<label class="layui-form-label">下期注意事项</label>
					<div class="layui-input-block">
						<textarea name="next_attention" placeholder="请输入内容" class="layui-textarea"></textarea>
					</div>
				</div>
				<div class="layui-form-item">
					<div class="layui-input-block">
						<button class="layui-btn" lay-submit="" lay-filter="addServiceMsgForm">立即提交</button>
						<button type="reset" class="layui-btn layui-btn-primary">重置</button>
					</div>
				</div>
			</form>
		</div>
	</div>
</div>

<script>
layui.use(['admin', 'form', 'view' ,'laydate','upload'], function () {
    var $ = layui.$
      , admin = layui.admin
      , element = layui.element
      , layer = layui.layer
      , laydate = layui.laydate
      , form = layui.form
	  , upload = layui.upload
	  , view = layui.view;
	  var imgId = [];
	  var maxImgNum = 9
	  $('#uploadQuestImg').html('')
	  
	  // 初次进入页面加载
	  if(JSON.parse(window.localStorage.getItem('addCustomersInfo')).id){
	  	 showInputValue()
		 imgId = [];
		 $('#uploadQuestImg').html('')
		 maxImgNum = 9
	  }
	  // 设置为暂时不需要刷新
	  var newLocal = window.localStorage.getItem('addCustomersInfo').replace('true','false');
	  window.localStorage.setItem('addCustomersInfo',newLocal);
	  console.log(JSON.parse(window.localStorage.getItem('addCustomersInfo')));
	  
	  // 当单页面进行切换时做出判断,判断是否需要刷新数据
	  window.onhashchange=function(event){
	  	setTimeout(function(){
	  		if(window.location.hash == '#/user/add'){
				if(JSON.parse(window.localStorage.getItem('addCustomersInfo')).reload == true){
					 imgId = [];
					 maxImgNum = 9
					 $('#uploadQuestImg').html('')
					
					$('.addServiceMsg')[0].reset();
					form.render();
					if(JSON.parse(window.localStorage.getItem('addCustomersInfo')).id){
						 showInputValue();
					}
					// 设置为暂时不需要刷新
					var newLocal = window.localStorage.getItem('addCustomersInfo').replace('true','false');
					window.localStorage.setItem('addCustomersInfo',newLocal);
					console.log(JSON.parse(window.localStorage.getItem('addCustomersInfo')));
				}
				  
	  		}
	  	},100)
	  }
	  
	  
	  function showInputValue(){
		   view.setTitle('修改田间服务信息')
		  $('.addTitle').text('修改田间服务信息')
		  // 修改时获取所有信息
		  $.ajax({
			  url: apiUrl + '/index.php/agricultural/Userindex/select?token=' + JSON.parse(window.sessionStorage.getItem('agricultural')).token,
			  data:{
				  id: JSON.parse(window.localStorage.getItem('addCustomersInfo')).id
			  },
			  type: 'POST',
			  success:function(res){
				console.log(res)
				if(res.code == 0){
					$.each(res.data[0],function(k,v){
						$('.addServiceMsg input[name=' + k + ']').val(v)
						$('.addServiceMsg textarea[name=' + k + ']').val(v)
						if(k == 'guide_time'){
							$('.addServiceMsg input[name=' + k + ']').val(v.substring(0,10))
						}
					})
					$.each(res.img,function(i,url){
						$('#uploadQuestImg').append('<img src="'+ url.img_path +'" class="layui-upload-img">')
						maxImgNum--;
						imgId.push(url.id)
					})
					console.log(imgId)
				}else if(res.code == 2){
					tokenExpired()
				}else{
					layer.msg(res.msg)
				}
				  
			  },
			  complete:function(){
				  //loading.hide();
			  }
		  });
	  }
	  

    form.render(null, 'form-group');

    laydate.render({
      elem: '#form-group-date'
    });
	
	// 点击上传图片触发
	$('#uploadImg').click(function(){
		var u = navigator.userAgent;
		if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {//安卓手机
			// alert("安卓手机");
			$('#btnHide').trigger("click");
		} else if (u.indexOf('iPhone') > -1) {//苹果手机
			// alert("苹果手机");
			$('#test2').trigger("click");
		} else{//winphone手机
			// alert("winphone手机");
			$('#btnHide').trigger("click");
		}
	})
	
	var loading = '';
	//多图片上传
	  upload.render({
		elem: '#test2'
		,url: apiUrl + '/index.php/agricultural/Index/uploadImgOss'
		,multiple: true
		,accept: 'images'
		,multiple: true
		,number: 9
		,field: 'img'
		,before: function(obj){
			console.log(maxImgNum)
			if(maxImgNum <= 0){
				layer.msg('最多允许上传9张图片');
				return false;
			}
			loading = layer.load(3, {
				shade: [0.1, '#000'] //0.1透明度的白色背景
			});
		}
		,done: function(res){
		  //上传完毕
		  imgId.push(res.img.img_id)
		  maxImgNum--;
		  console.log(imgId)
		  $('#uploadQuestImg').append('<img src="'+ res.img.img_path +'" class="layui-upload-img">')
		  
		},
		allDone: function(obj){ //当文件全部被提交后，才触发
			layer.closeAll('loading');
		}
	  });
	  
	
	
	
	// 上传
	$(document).on('input','#btnHide',function() {
		// 获取图片大小,判断是否需要压缩
		var files = this.files;
		var thisElem = this
		console.log(files)
		console.log(maxImgNum)
		if(maxImgNum <= 0){
			layer.msg('最多允许上传9张图片');
			return false;
		}
		loading = layer.load(3, {
			shade: [0.1, '#000'] ,//0.1透明度的白色背景
			success: function(layero, index){
				setTimeout(function() {
					console.log(1111111111111111)
					$.each(files,function(i,imgData){
						if(imgData.size>150 * 1024){
							console.log('需要压缩')
							let z = new zz();
							z.compressPhotoUpload({
								elem: thisElem,		//必传，上传图片的input元素
								index: i,		//必传，上传图片的input元素
								ratio: 0.3,		//默认为0.1   压缩比
								maxsize: 0.2,	//默认为1024,单位为kb    大于此值则做压缩操作
								success: (e) => {	//必传，成功后的回调函数，返回的参数是图片信息（对象）
									console.log(e);
									var newFile = dataURLtoFile(e.data,'11')
									console.log(newFile)
									if(i == files.length-1){
										layer.closeAll('loading');
									}
									up(newFile);
								}
							});
						}else{
							console.log('不需要压缩',i)
							if(i == files.length-1){
								layer.closeAll('loading');
							}
							up(imgData);
						}
					})
				}, 500);
			}
		});
		
		
		
	})
	
	function dataURLtoFile(dataurl, filename) {
	  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
	  bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
	  while(n--){
		  u8arr[n] = bstr.charCodeAt(n);
	  }
	  return new File([u8arr], filename, {type:mime});
	}
	
	// 上传接口
	function up(e){
		var formdata = new FormData()
		console.log(e)
		formdata.append('img', e)
		console.log(formdata)
		$.ajax({
			url: apiUrl + '/index.php/agricultural/Index/uploadImgOss',
			dataType: 'json',
			type: 'POST',
			async: false,
			data: formdata,
			processData: false, // 使数据不做处理
			contentType: false, // 不要设置Content-Type请求头
			success: function(res) {
				console.log(res);
				if (res.code == 0) {
					$('#uploadQuestImg').append('<img src="'+ res.img.img_path +'" class="layui-upload-img">')
					imgId.push(res.img.img_id)
					console.log(imgId)
				} else {
					layer.msg(res.msg);
				}
			}
		});
	}
    
    /* 监听提交 */
    form.on('submit(addServiceMsgForm)', function (data) {
		data.field.agriculture_user_id = JSON.parse(window.localStorage.getItem('addCustomersInfo')).cid
		var is_remind = isMobile()
		is_remind = is_remind ? '1' : ''
		data.field.is_remind = is_remind
		delete data.field['file'];
		delete data.field['img'];
		data.field.imgid = imgId.join(",");
		console.log(data.field)
		
		if(JSON.parse(window.localStorage.getItem('addCustomersInfo')).id){
			data.field.id = JSON.parse(window.localStorage.getItem('addCustomersInfo')).id
			// 修改
			$.ajax({
			    url: apiUrl + '/index.php/agricultural/guide/updateData?token=' + JSON.parse(window.sessionStorage.getItem('agricultural')).token,
			    data:data.field,
				type: 'POST',
			    success:function(res){
					console.log(res)
					if(res.code == 0){
						layer.msg(res.msg)
						setTimeout(function(){
							view.tab.del('/user/add');
							admin.navigate('/user/index')
						},2000)
					}else if(res.code == 2){
						tokenExpired()
					}else{
						layer.msg(res.msg)
					}
			        
			    },
			    complete:function(){
			        //loading.hide();
			    }
			});
		}else{
			// 添加
			$.ajax({
			    url: apiUrl + '/index.php/agricultural/guide/addData?token=' + JSON.parse(window.sessionStorage.getItem('agricultural')).token,
			    data:data.field,
				type: 'POST',
			    success:function(res){
					console.log(res)
					if(res.code == 0){
						layer.msg(res.msg)
						setTimeout(function(){
							view.tab.del('/user/add');
							admin.navigate('/user/index')
						},2000)
					}else if(res.code == 2){
						tokenExpired()
					}else{
						layer.msg(res.msg)
					}
			        
			    },
			    complete:function(){
			        //loading.hide();
			    }
			});
		}
		return false;
		
    });
  });
</script>


<style type="text/css">
	.addServiceMsg .layui-form-label {
		width: 130px;
	}

	.addServiceMsg .layui-input-block {
		margin-left: 165px;
	}

	#uploadQuestImg img {
		width: 120px;
		height: 120px;
		object-fit: cover;
		margin-right: 20px;
	}

	.uploadImgBlock {
		margin-top: 10px;
	}

	.longInput {
		width: 500px;
	}

	@media screen and (max-width: 768px) {
		.addServiceMsg .layui-form-label {
			width: auto;
			float: none;
			text-align: left;
			padding: 0 0 5px 2px;
		}

		.addServiceMsg .layui-input-block {
			margin-left: 0;
		}

		.addServiceMsg .layui-form-item .layui-input-inline {
			margin-left: 0;
		}

		#uploadQuestImg img {
			width: 45%;
			height: 120px;
			object-fit: cover;
			margin: 10px 2%;
		}

		.longInput {
			width: 100%;
		}
	}
</style>
